package Offer.offer;

/**
 * 按年龄排序
 * @author leiwenkang
 * @date 2020/4/6
 */
public class Test07c按年龄排序 {
    public static void main(String[] args) {
        int[] ages = {5,3,7,15,7,2,6,3,6,2,66,7,2,78,24,23,67};
        sortAge(ages);
        for (int i = 0; i < ages.length; i++) {
            System.out.print(ages[i]);
            System.out.print(" ");
        }
    }

    public static void sortAge(int[] ages) {
        if (ages == null || ages.length == 0) {
            return;
        }

        int oldestAge = 99;
        //初始化
        int[] timesOfAge = new int[oldestAge + 1];
        for (int i = 0; i < timesOfAge.length; i++) {
            timesOfAge[i] = 0;
        }

        for (int age : ages) {
            if (age < 0 || age > oldestAge) {
                throw new RuntimeException("非法年龄");
            }
            timesOfAge[age]++;
        }

        //替换原来的ages数组
        int index = 0;
        for (int i = 0; i < timesOfAge.length; i++) {
            int time = timesOfAge[i];
            for (int j = 0; j < time; j++) {
                ages[index++] = i;
            }
        }

    }
}
